<!-- 聊天消息中心列表页面 -->
<template>
	<view :style="mix_diyStyle">
  <view class="message_center">
    <!-- #ifdef MP -->
    <view class="message_center_nav-bar" :style="{ paddingTop: menuButtonTop }">
    	<view class="nav-bar" :style="{ height: menuButtonHeight }">
    		<image :src="imgUrl + 'fanhui1.png'" mode="" @click="$back"></image>
    		<view class="">{{ $L('消息中心') }}</view>
        <view class="nav-bar_close flex_row_center_center" @click="cleanUp">
          <image :src="imgUrl+'clearUnread.png'" mode=""></image>
          <text class="">{{ $L('清除未读') }}</text>
        </view>
       <!-- <view class="nav-bar_close flex_row_center_center" style="margin-left: 38rpx;" @click="goNoticeSet">
          <image :src="imgUrl+'messageSettings.png'" mode=""></image>
          <text class="">{{ $L('设置') }}</text> 
        </view> -->
    	</view>
    </view>
    <view class="" :style="{ paddingTop: menuButtonTop,paddingBottom:'20rpx',borderTop:'1rpx solid #f2f2f2', }">
    	<view class="nav-bar" :style="{ height: menuButtonHeight }"></view>
    </view>
    <!-- #endif -->
    <!-- #ifdef APP -->
      <view class="message_center_nav-bar nav-bar_app" >
      	<view class="nav-bar">
      		<image :src="imgUrl + 'fanhui1.png'" mode="" @click="$back"></image>
      		<view class="">{{ $L('消息中心') }}</view>
          <view class="nav-bar_close flex_row_center_center" @click="cleanUp">
            <image :src="imgUrl+'clearUnread.png'" mode=""></image>
            <text class="">{{ $L('清除未读') }}</text>
          </view>
          <view class="nav-bar_close flex_row_center_center" style="margin-left: 38rpx;" @click="goNoticeSet">
            <image :src="imgUrl+'messageSettings.png'" mode=""></image>
            <text class="">{{ $L('设置') }}</text>
          </view>
      	</view>
      </view>
      <view class="nav-bar_apps" style="padding-bottom: 20rpx;">
      	<view class="nav-bar"></view>
      </view>
    <!-- #endif -->
    <!-- #ifdef H5 -->
      <view class="message_center_nav-bar nav-bar_apps nav-bar_h5 flex_row_between_center">
      	<view class="nav-bar flex_row_end_center">
          <view class="nav-bar_close flex_row_center_center" @click="cleanUp">
            <image :src="imgUrl+'clearUnread.png'" mode=""></image>
            <text class="">{{ $L('清除未读') }}</text>
          </view>
          <view class="nav-bar_close flex_row_center_center" style="margin-left: 38rpx;" @click="goNoticeSet">
            <image :src="imgUrl+'messageSettings.png'" mode=""></image>
            <text class="">{{ $L('设置') }}</text>
          </view>
      	</view>
      </view>
    <!-- #endif -->
    <!-- 消息类型 start -->
   <!-- <scroll-view class="message_type" scroll-x="true" @scroll="scrollView">
      <view class="message_type_con">
        <view
          class="message_type_pre"
          v-for="(item, index) in noticeList"
          :key="index"
          @click="linkTo(item.tplTypeCode, item.msgNum)"
        >
          <image
            :src="system_news"
            mode="aspectFit"
            v-if="item.tplTypeCode == 'system_news'"
          ></image>
          <image
            :src="order_news"
            mode="aspectFit"
            v-if="item.tplTypeCode == 'order_news'"
          ></image>
          <image
            :src="assets_news"
            mode="aspectFit"
            v-if="item.tplTypeCode == 'assets_news'"
          ></image>
          <image
            :src="appointment_news"
            mode="aspectFit"
            v-if="item.tplTypeCode == 'appointment_news'"
          ></image>
          <image
            :src="after_sale_news"
            mode="aspectFit"
            v-if="item.tplTypeCode == 'after_sale_news'"
          ></image>
          <text>{{ item.msgName }}</text>
          <text
            class="message_type_nums message_type_nums_9"
            v-if="item.msgNum > 0"
            >{{ item.msgNum >= 99 ? '99+' : item.msgNum }}</text
          >
        </view>
      </view>
    </scroll-view> -->
    <!-- 消息类型 end -->
    <!-- 消息列表 start -->
    <view class="message_list">
      <view
        class="message_list_pre"
        @touchmove="drawMove"
        @toucheend="drawEnd"
        :style="{ right: optBtn && _index == index ? '240rpx' : '0rpx' }"
        v-for="(item, index) in chatList"
        :key="index"
        :data-index="index"
        @touchstart="drawStart"
        @click="toDetail(item)"
      >
        <view class="list_pre_left">
          <image :src="item.vendorAvatar" mode="aspectFill"></image>
        </view>
        <view class="list_pre_con">
          <view class="list_pre_top">
            <text class="pre_name">{{ item.storeName }}</text>
            <text class="list_pre_time">{{ item.addTime }}</text>
          </view>
          <view class="list_pre_bottom">
            <text class="pre_des">{{ item.showContent }}</text>
            <text
              v-if="item.receiveMsgNumber"
              class="list_pre_nums9 list_pre_nums"
              >{{
                item.receiveMsgNumber >= 99 ? '99+' : item.receiveMsgNumber
              }}</text
            >
          </view>
        </view>
        <view class="list_pre_btn">
          <text class="list_btn_read" @click.stop="msgReadDone(item.storeId)">{{
            $L('已读')
          }}</text>
          <text class="list_btn_del" @click.stop="msgDelete(item.storeId)">{{
            $L('删除')
          }}</text>
        </view>
      </view> 
      <loadingState
        v-if="loadingState == 'first_loading' || chatList.length > 0"
        :state="loadingState"
      />
      <view class="empty_data" v-if="!chatList.length > 0">
        <image :src="imgUrl + 'empty_msg.png'" mode="aspectFit"></image>
        <text>{{ $L('暂无消息记录') }}</text>
      </view>
    </view>
    <!-- 消息列表 end -->
  </view>
	</view>
</template>

<script>
import loadingState from '@/components/loading-state.vue'
import { mapState, mapMutations } from 'vuex'
import io from '@hyoga/uni-socket.io'

export default {
  components: {
    loadingState
  },
  data() {
    return {
      // #ifdef MP
      menuButtonHeight: uni.getMenuButtonBoundingClientRect().height + 'px',
      menuButtonTop: uni.getMenuButtonBoundingClientRect().top + 'px',
      menuButtonleft:uni.getMenuButtonBoundingClientRect().left+'px',
      // #endif
      connectBaseData: {}, //每次通信必传信息
      imgUrl: getApp().globalData.imgUrl,
      assets_news: getApp().globalData.imgUrl + 'member/icon10.png',
      order_news: getApp().globalData.imgUrl + 'member/icon20.png',
      after_sale_news: getApp().globalData.imgUrl + 'member/icon30.png',
      system_news: getApp().globalData.imgUrl + 'member/icon60.png',
      appointment_news: getApp().globalData.imgUrl + 'member/icon70.png',
      setting_icon: getApp().globalData.imgUrl + 'member/receive_settings.png',
      startX: '',
      optBtn: false, //操作按钮是否显示（已读，删除）
      current: 1,
      hasMore: true, //是否还有数据
      pageSize: 10,
      loadingState: 'first_loading',
      chatList: [],
      noticeList: [],
      minMsgId: '', //当前消息的最小id
      socketInfo: '', //socket连接成功返回的房间信息
      _index: '',
      showState: false,
      leftNum: '0'
    }
  },
  async onLoad() {
    setTimeout(()=>{
        uni.setNavigationBarTitle({
          title: this.$L('消息中心')
        })  
    },0);
    
    await this.getChatList()
    this.initSocket()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if (this.socket) {
      this.closeSocket()
    }
    this._index = ''
  },
  computed: {
    ...mapState(['userInfo', 'userCenterData'])
  },

  onBackPress() {
    this.closeSocket()
  },

  onShow() {
    this.getNoticeNum()
    if (this.showState) {
      this.initSocket()
    }
  },

  onHide() {
    this._index = ''
  },

  methods: {
    ...mapMutations(['saveChatBaseInfo']),
    // 一键已读
    cleanUp(){
      let param = {}
      param.url = 'v3/msg/front/msg/read'
      param.method = 'POST'
      param.data={}
      param.data.isAllRead = true
      param.data.isPc = false
      this.$request(param).then((res) => {
        if (res.state == 200) {
          this.current = 1
          this.minMsgId = ''
          this.initSocket()
          this.getNoticeNum()
          this.getChatList()
          this.$api.msg(res.msg)
        } else {
          this.$api.msg(res.msg)
        }
      })
    },
    scrollView(e) {
      let num = (e.detail.scrollLeft * 17 * (this.noticeList.length + 1)) / 100
      this.leftNum = num + 'rpx'
    },
    initSocket() {
      if (this.socket) {
        this.closeSocket()
      }
      this.connectBaseData = {
        userId: this.userCenterData.memberId,
        role: 1
      }
      this.socket = io(getApp().globalData.chatUrl, {
        reconnection: true,
        jsonp: true,
        transports: ['websocket', 'polling'],
        timeout: 5000
      })
      this.socket.on('connect', () => {
        //需要向服务端发送店铺id，方便加入房间
        if (this.chatList.length > 0) {
          this.sendStoreIds()
        }
        //监听最近联系人列表
        this.socket.on('contact_change', (e) => {
          let tmp_data = this.chatList.filter(
            (item) => item.storeId != e.storeId
          )
          tmp_data.unshift(e)
          this.chatList = tmp_data
          this.formatMsgContent()
        })
        //监听未读数
        this.socket.on('unread_num_change', (e) => {
          let tmp_data = this.chatList.filter(
            (item) => item.storeId == e.storeId
          )
          if (tmp_data.length == 1) {
            tmp_data[0].receiveMsgNumber = e.unreadNum
          }
        })
      })
    },
    // 发送当前列表的所有店铺id
    sendStoreIds() {
      let tmpStoreIdArray = []
      this.chatList.map((item) => {
        tmpStoreIdArray.push(item.storeId)
      })
      this.socket.emit('send_store_ids', {
        storeIds: tmpStoreIdArray.join(','),
        ...this.connectBaseData
      })
      this.socket.emit('connect_success', {
        storeId: '',
        ...this.connectBaseData
      })
    },
    //关闭socket
    closeSocket() {
      if (this.socket) {
        this.socket.close()
      }
    },
    //开始触摸滑动
    drawStart(e) {
      let index = e.currentTarget.dataset.index
      this._index = index
      let touch = e.touches[0]
      this.startX = touch.clientX
    },
    //触摸滑动
    drawMove(e) {
      let touch = e.touches[0]
      let dixX = this.startX - touch.clientX
      if (dixX >= 20) {
        this.optBtn = true
      } else {
        this.optBtn = false
      }
    },
    //触摸滑动结束
    drawEnd(e) {
      this.optBtn = false
    },

    //去消息设置页面
    goNoticeSet() {
      this.$Router.push('/pages/notice/receivingSet')
    },

    //导航栏跳转页面
    linkTo(tplTypeCode, msgNum) {
      this.$Router.push({
        path: '/pages/notice/notice',
        query: {
          tplType: tplTypeCode
        }
      })
    },

    //聊天标记为已读,将未读数置为0
    msgReadDone(storeId) {
      let _this = this
      this.socket.emit('member_read_all', {
        ...this.connectBaseData,
		storeId
      })
      let tmpData = _this.chatList.filter((item) => item.storeId == storeId)[0]
      tmpData.receiveMsgNumber = 0
      _this.chatList = _this.chatList
      this.optBtn = false
    },
    //删除聊天
    msgDelete(storeId) {
      let _this = this
      uni.showModal({
        title: _this.$L('提示'),
        content: _this.$L('是否删除该聊天？'),
        success: (res) => {
          if (res.confirm) {
            _this.socket.emit(
              'member_remove_contact',
              {
                storeId: storeId,
                ...this.connectBaseData
              },
              () => {
                _this.chatList = _this.chatList.filter(
                  (item) => item.storeId != storeId
                )
              }
            )

            _this.optBtn = false
            _this._index = ''
          } else {
            _this.optBtn = false
          }
        }
      })
    },

    //获取消息未读数
    getNoticeNum() {
      let param = {}
      param.url = 'v3/msg/front/msg/msgListNum'
      param.method = 'GET'
      this.$request(param).then((res) => {
        if (res.state == 200) {
          this.noticeList = res.data
        } else {
          this.$api.msg(res.msg)
        }
      })
    },
    //获取聊天列表
    async getChatList() {
      let params = {}
      ;(params.url = 'v3/helpdesk/front/chat/storeList'),
        (params.method = 'GET')
      params.data = {}
      params.data.pageSize = this.pageSize
      params.data.current = this.current
      if (this.minMsgId) {
        params.data.msgId = this.minMsgId
      }
      this.loadingState =
        this.loadingState == 'first_loading' ? this.loadingState : 'loading'
      await this.$request(params).then((res) => {
        if (res.state == 200) {
          if (this.current == 1) {
            this.chatList = res.data
          } else {
            this.chatList = this.chatList.concat(res.data)
          }
          if (this.minMsgId) {
            this.sendStoreIds()
          }
          if (this.chatList.length > 0) {
            this.minMsgId = this.chatList[this.chatList.length - 1].msgId
          }
          if (res.data.length < this.pageSize) {
            this.hasMore = false
          }

          if (this.hasMore) {
            this.current++
            this.loadingState = 'allow_loading_more'
          } else {
            this.loadingState = 'no_more_data'
          }
          this.formatMsgContent()
        } else {
          this.$api.msg(res.msg)
          this.loadingState = 'no_more_data'
        }
      })
    },

    //格式化聊天内容，方便列表展示
    formatMsgContent() {
      let reg = /<img[^>]*>/g
      let reg4 = /(<\/?div.*?>)|(<\/?br.*?>)|(<\/?span.*?>)/g

      if (this.chatList.length > 0) {
        this.chatList.map((item) => {
          if (typeof item.msgContent == 'string') {
            item.msgContent = JSON.parse(item.msgContent)
          }
          //1.text(文本) 2.img(图片) 3.goods(商品) 4.order(订单)用户
          if (item.msgType == 1) {
            if (reg.test(item.msgContent.content)) {
              item.msgContent.content = item.msgContent.content.replace(
                reg,
                '[表情]'
              )
              item.showContent = item.msgContent.content
            } else {
              item.showContent = item.msgContent.content
            }

            if (reg4.test(item.msgContent.content)) {
              item.msgContent.content = item.msgContent.content.replace(
                reg4,
                ''
              )
              item.showContent = item.msgContent.content
            } else {
              item.showContent = item.msgContent.content
            }
          } else if (item.msgType == 2) {
            item.showContent = this.$L('[图片]')
          } else if (item.msgType == 3) {
            item.showContent = this.$L('[商品]')
          } else if (item.msgType == 4) {
            item.showContent = this.$L('[订单]')
          }
        })
      }
    },

    onReachBottom() {
      if (this.hasMore) {
        getChatList()
      }
    },

    //前往聊天界面
    toDetail(item) {
      let chatBaseInfo = {}
      chatBaseInfo.memberId = item.memberId
      chatBaseInfo.memberName = item.memberName
      chatBaseInfo.memberNickName = item.memberName
      chatBaseInfo.memberAvatar = item.memberAvatar
      chatBaseInfo.storeId = item.storeId
      chatBaseInfo.storeLogo = item.vendorAvatar
      chatBaseInfo.storeName = item.storeName
      chatBaseInfo.source = 'chat_list'
      chatBaseInfo.showData = {}
      this.saveChatBaseInfo(chatBaseInfo)
      this.showState = true
      this.$Router.push({
        path: '/standard/chat/detail',
        query: {
          vid: item.storeId
        }
      })
    }
  }
}
</script>

<style lang="scss">
page {
  background: #ffffff;
}

.message_center {
  width: 750rpx;
  margin-left: calc((100vw - 750rpx) / 2);

  /* 消息类型 start */
  .message_type {
    height: 180rpx;
    padding: 0rpx 20rpx 24rpx;
    /* #ifndef H5 */
    border-top: 1rpx solid #f2f2f2;
     /* #endif */
    display: flex;
    /* #ifdef MP */
    // margin-top: 20rpx;
    /* #endif */

    .message_type_con {
      padding-right: 20rpx;
      padding-top: 24rpx;
      display: flex;
      position: relative;

      .message_type_pre {
        margin-right: 38rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        position: relative;

        image {
          width: 70rpx;
          height: 70rpx;
        }

        text {
          font-size: 28rpx;
          font-family: PingFang SC;
          font-weight: 500;
          color: #2d2d2d;
          line-height: 32rpx;
          margin-top: 20rpx;
          white-space: nowrap;
        }

        .message_type_nums {
          position: absolute;
          right: 18rpx;
          top: -28rpx;
          min-width: 22rpx;
          height: 22rpx;
          background: var(--color_main);
          border-radius: 13rpx;
          font-size: 20rpx;
          font-family: PingFang SC;
          font-weight: 400;
          color: #ffffff;
          line-height: 22rpx;
          text-align: center;
        }

        .message_type_nums_9 {
          padding: 0 5rpx;
          /* height: 22rpx; */
        }
      }

      .message_type_pre:nth-last-of-type(1) {
        margin-right: 0;
      }
    }
  }
  /* 消息类型 end */

  .prograss {
    overflow: hidden;
    width: 120rpx;
    height: 8rpx;
    background: #dedede;
    border-radius: 8rpx;
    margin: 0 auto 16rpx;
    .prograss_on {
      width: 60rpx;
      height: 8rpx;
      background: #6982fd;
      border-radius: 8rpx;
    }
  }

  /* 消息列表 start */
  .message_list {
    border-top: 20rpx solid #f5f5f5;
    overflow-x: hidden;

    .message_list_pre {
      display: flex;
      align-items: center;
      margin: 0 20rpx;
      border-bottom: 1rpx solid #f2f2f2;
      height: 150rpx;
      position: relative;
      transition: all 0.3s;

      .message_list_pre:last-child {
        border: none;
      }

      .list_pre_left {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        margin-right: 30rpx;

        image {
          width: 80rpx;
          height: 80rpx;
          border-radius: 50%;
        }
      }

      .list_pre_con {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        align-items: space-between;
        width: 620rpx;
        padding: 40rpx 0;
        height: 150rpx;
        box-sizing: border-box;

        .list_pre_top {
          display: flex;
          justify-content: space-between;

          .pre_name {
            font-size: 30rpx;
            font-family: PingFang SC;
            font-weight: 500;
            color: #333333;
            line-height: 30rpx;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          .list_pre_time {
            font-size: 22rpx;
            font-family: PingFang SC;
            font-weight: 500;
            color: #999999;
            line-height: 32rpx;
          }
        }

        .list_pre_bottom {
          display: flex;
          justify-content: space-between;

          .pre_des {
            width: 484rpx;
            font-size: 26rpx;
            font-family: PingFang SC;
            font-weight: 500;
            color: #999999;
            line-height: 28rpx;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            height: 30rpx;
          }

          .list_pre_nums {
            height: 22rpx;
            background: #ff0000;
            border-radius: 10rpx;
            text-align: center;
            line-height: 22rpx;
            font-size: 20rpx;
            font-family: PingFang SC;
            font-weight: 500;
            color: #ffffff;
            line-height: 22rpx;
          }

          .list_pre_nums9 {
            position: absolute;
            left: 48rpx;
            top: 24rpx;
            padding: 0 4rpx;
            min-width: 22rpx;
          }
        }
      }

      .list_pre_btn {
        display: flex;
        align-items: center;
        position: absolute;
        top: 0;
        right: -260rpx;

        .list_btn_read {
          width: 120rpx;
          height: 150rpx;
          background: #eeeeee;
          font-size: 28rpx;
          font-family: PingFang SC;
          font-weight: 500;
          color: #333333;
          line-height: 150rpx;
          text-align: center;
        }

        .list_btn_del {
          width: 120rpx;
          height: 150rpx;
          background: #ff0000;
          font-size: 28rpx;
          font-family: PingFang SC;
          font-weight: 500;
          color: #ffffff;
          line-height: 150rpx;
          text-align: center;
        }
      }
    }
  }

  /* 消息列表 end */
}

.empty_data {
  height: 750rpx;
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;

  image {
    width: 380rpx;
    height: 280rpx;
  }

  text {
    margin-top: 20rpx;
    font-size: 28rpx;
    color: #999999;
  }
}
.nav-bar {
	width: 100%;
  /* #ifndef H5 */
	display: flex;
	align-items: center;
	justify-content: flex-start;
  /* #endif */
	padding:0 20rpx;
  z-index: 9;
}

.nav-bar image {
	width: 21rpx;
	height: 35rpx;
}

.nav-bar view {
	font-size: 36rpx;
	font-family: PingFang SC;
	color: #000;
	margin-left: 21rpx;
}
.message_center_nav-bar{
   /* #ifndef H5 */
  position: fixed;
  padding-bottom: 20rpx;
  /* #endif */
  /* #ifdef MP */
  border-top: 1rpx solid #f2f2f2;
  /* #endif */
  width: 100%;
  background: #fff;
  z-index: 999;
  .nav-bar{
    z-index: 999;
  }
  .nav-bar_close{
    image{
      width: 31rpx;
      height: 30rpx;
      margin-top: 2rpx;
    }
    text{
      margin-left: 5rpx;
      font-size: 28rpx;
      font-family: PingFang SC;
      font-weight: 500;
      color: #999999;
    }
  }
}
.nav-bar_app{
  padding-top: calc(var(--status-bar-height) + 15rpx);
  .nav-bar{
    height: 50rpx;
  }
}
.nav-bar_apps{
  padding-top: calc(var(--status-bar-height) + 15rpx);
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f2f2f2;
  .nav-bar{
    width: 100%;
    height: 50rpx;
  }
}
.nav-bar_h5{
  width: 750rpx;
  .nav-bar{
    flex: 1;
    height: 50rpx;
  }
}
</style>
